﻿using Quartz;
using Share;

namespace ContinuousJobs.Jobs;

public class ContinuousJobListener : IJobListener
{
    public string Name => nameof(ContinuousJobListener);

    public Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
    {
        return Task.CompletedTask;
    }

    public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
    {
        return Task.CompletedTask;
    }

    public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
    {
        if (context.JobInstance is IHasNextJob hasNext)
        {
            IJobDetail nextJob = hasNext.NextJob;
            if (nextJob != null)
            {
                Console.WriteLine($"当前 job is {context.JobDetail.Key.Name}, Next is {nextJob.Key.Name}");

                IScheduler scheduler = context.Scheduler;
                //IJobDetail next=JobBuilder.Create()
                //IJobDetail nextJob = JobBuilder.Create<FirstJob>() // 这里需要根据 nextJobKey 动态创建
                //    .WithIdentity(next)
                //    .Build();
                ITrigger nextTrigger = TriggerBuilder.Create()
                    .WithIdentity(nextJob.Key.Name)
                    .ForJob(nextJob)
                    .StartNow()
                    .Build();
                await scheduler.ScheduleJob(nextTrigger, cancellationToken);
            }
            else
            {
                Console.WriteLine($"当前 job is {context.JobDetail.Key.Name}, 已是最后一个作业");
            }
        }
    }
}
